package com.jusda.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author:y022 12/06/2022 18:24
 * @description: 模拟mq实现原理, 开启两个线程分别代生产者和消费者，使用LinkedBlockingDeque来作为消费的存储容器，即broker的概念。
 */
public class MqUtils {
    private static LinkedBlockingDeque<JSONObject> mqQueue = new LinkedBlockingDeque<JSONObject>();

    private static Thread getProducer(String producerName) {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int i = 0;
                    while (true) {
                        JSONObject msg = new JSONObject();
                        msg.put("userId", ++i);
                        Thread.sleep(1000);
                        mqQueue.offer(msg);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, producerName);
    }

    private static Thread getConsumer(String consumerName) {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                Thread.currentThread().setName(consumerName);
                try {
                    while (true) {
                        if (!mqQueue.isEmpty()) {
                            System.out.println(Thread.currentThread().getName() + "，取得消息：" + mqQueue.poll());
                        }
                    }
                } catch (Exception e) {
                    System.out.println("消息消费失败" + e);
                }
            }
        });
    }

    public static void main(String[] args) {
        getProducer("生产者1号").start();
        getConsumer("消费者1号").start();
    }
}
